package cn.gson.school.controller.caiwu;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;
import javax.transaction.Transactional;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.school.dao.caiwu.ShouKuanDao;
import cn.gson.school.dao.caiwu.ShouKuanInfoDao;
import cn.gson.school.dao.jiaoxue.ClassDao;
import cn.gson.school.dao.jiaoxue.StudentDao;
import cn.gson.school.dao.xitong.UserDao;
import cn.gson.school.dao.xitong.UserInfoDao;
import cn.gson.school.entity.caiwu.ShouKuanEntity;
import cn.gson.school.entity.caiwu.ShouKuanInfoEntity;
import cn.gson.school.entity.jiaoxue.ClassEntity;
import cn.gson.school.entity.jiaoxue.StudentEntity;
import cn.gson.school.entity.xitong.ImageEntity;
import cn.gson.school.entity.xitong.UserEntity;
import cn.gson.school.entity.xitong.UserInfoEntity;
import cn.gson.school.mappers.caiwu.ShouKuanMapper;
import cn.gson.school.service.ImagesService;

@Controller
@RequestMapping("/cw-shoukuan-list")
public class ShouKuanController {

	@Autowired
	private ShouKuanMapper shoukuanMapper;
	// 收款
	@Autowired
	private ShouKuanDao shoukuanDao;
	// 收款详情
	@Autowired
	private ShouKuanInfoDao shoukuaninfoDao;
	// 学生详情
	@Autowired
	private StudentDao studentDao;
	// 班级
	@Autowired
	private ClassDao classDao;

	// 班级
	@Autowired
	private UserInfoDao userInfoDao;
	//图片
	@Autowired
	private ImagesService imgService;

	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> index(ShouKuanEntity shoukuan,
			@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize) {

		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<ShouKuanEntity> pageData = shoukuanMapper.shoukuanlist(shoukuan);
		PageInfo<ShouKuanEntity> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}

	/**
	 * 表单
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping({ "cw-add-shoukuan", "cw-add-shoukuan/{id}" })
	public String form(@PathVariable(name = "id", required = false) Long id, Model model) {
		System.out.println("查到的id:" + id);
		if (id != null) {
			ShouKuanEntity shoukuan = shoukuanDao.findOne(id);
			if (shoukuan != null) {
				// 如果是编辑，则把原有用户信息传回表单页面
				model.addAttribute("shoukuanEntity", shoukuan);

				// 获取班级id
				ClassEntity csentity = shoukuan.getClassId();
				model.addAttribute("classEntity", csentity);
				// 获取学生id
				StudentEntity stentity = shoukuan.getStudent();
				model.addAttribute("studentEntity", stentity);
			}
		}
		// 班级
		Iterable<ClassEntity> list = classDao.findByDelete(1);
		model.addAttribute("classList", list);
		// 学生
		Iterable<StudentEntity> student = studentDao.findAll();
		model.addAttribute("studentList", student);
		return "caiwu/cw-add-shoukuan";
	}

	/**
	 * 添加
	 * 
	 * @throws ParseException
	 */
	@SuppressWarnings("unlikely-arg-type")
	@PostMapping("/save")
	@ResponseBody
	@Transactional
	public Map<String, Object> save(HttpSession session,@Valid ShouKuanEntity shouKuan, HttpServletRequest request, Model model,
			@SessionAttribute("user") UserEntity user,@RequestParam("file")MultipartFile file,BindingResult br) throws ParseException {
		Map<String, Object> obj = new HashMap<String, Object>();
		//获取用户
		UserInfoEntity userInfoEntity =	(UserInfoEntity) session.getAttribute("userinfo");
		obj.put("success", false);
		if (br.hasErrors()) {
			obj.put("message", "校验失败！");
			obj.put("erros", br.getFieldErrors());
		} else {
			// 获取表单值
			String shoukuanid = request.getParameter("shoukuanid");// 收款id

			String shouKuanName = request.getParameter("shouKuanName");// 收款项目
			String lend = request.getParameter("lend");// 是否优惠
			String discountMoney = request.getParameter("discountMoney");// 优惠金额
			String shouKuanMoney = request.getParameter("shouKuanMoney");// 收款金额
			String shouKuanPay = request.getParameter("shouKuanPay");// 支付方式
			String discountReason = request.getParameter("discountReason");// 优惠原因
			String addPlus = request.getParameter("addPlus");// 备注
			String money = request.getParameter("money");// 应收金额
			String owedMoney = request.getParameter("owedMoney");// 还欠金额
			String payTime = request.getParameter("payTime");// 收款时间
			
			
			String className = request.getParameter("className");// 班级名称
			ClassEntity classEntity = classDao.findOne(Long.valueOf(className));
			System.out.println("班级名称：" + classEntity);

			String studentName = request.getParameter("studentName");// 学生姓名
			StudentEntity studentEntity = studentDao.findOne(Long.valueOf(studentName));// 学生名称
			System.out.println("学生名称：" + studentEntity);

			ShouKuanEntity shouKuanEntity;
			ShouKuanInfoEntity shouKuanInfoEntity;
			
			
			// 如果收款id=null就是添加否则就是编辑
			if (shoukuanid == null || "".equals(shoukuanid)) {
				shouKuanEntity = new ShouKuanEntity();
				shouKuanInfoEntity = new ShouKuanInfoEntity();
				shouKuanInfoEntity.setPayTime(new Date());
			} else {
				shouKuanEntity = shoukuanDao.findOne(Long.valueOf(shoukuanid));
				shouKuanEntity.setShoukuanId(Long.valueOf(shoukuanid));
				shouKuanInfoEntity = shoukuaninfoDao.findOne(shouKuanEntity.getShoukuaninfoId().getShoukuanInfoId());
			}
			/**
			 * 正则表达式
			 */
			Pattern pattern = Pattern.compile("(^[1-9](\\d+)?(\\.\\d{1,2})?$)|(^(0){1}$)|(^\\d\\.\\d{1,2}?$)"); // 判断小数点后2位的数字的正则表达式

			shouKuanEntity.setStudent(studentEntity);// 学生名称
			shouKuanEntity.setClassId(classEntity);// 班级名称

			shouKuanEntity.setLend(Integer.valueOf(lend));// 是否优惠 1
			shouKuanEntity.setShouKuanPay(shouKuanPay);// 支付方式 1
			shouKuanEntity.setDiscountReason(discountReason);// 优惠原因 1
			shouKuanInfoEntity.setAddPlus(addPlus);// 备注 1
			
			//文件上传
			ImageEntity img = null;
			try {
				img = imgService.upload(user, "sign", file,"");
			} catch (Exception e) {
				obj.put("上传失败！", e);
			}
			System.out.println("图片："+img);
			shouKuanEntity.setImagesId(img);
			
			if (shouKuanName != null && !" ".equals(shouKuanName) && !shouKuanName.matches("^[a-zA-Z]*")) {
				shouKuanEntity.setShouKuanName(shouKuanName);// 收款项目
			} else {
				obj.put("message", "收款项目输入有误！");
				return obj;
			}
			
			Matcher matchdm = pattern.matcher(discountMoney);
			if (matchdm.matches() == false) {
				obj.put("message", "优惠金额输入有误！");
				return obj;
			} else {
				shouKuanEntity.setDiscountMoney(Double.valueOf(discountMoney));// 优惠金额
			}

			Matcher matchmy = pattern.matcher(money);
			if (matchmy.matches() == false) {
				obj.put("message", "应收金额输入有误！");
				return obj;
			} else {
				shouKuanInfoEntity.setMoney(Double.valueOf(money));// 应收金额
			}
			
			Matcher matchskm = pattern.matcher(shouKuanMoney);
			if (matchskm.matches() == false) {
				obj.put("message", "收款金额输入有误！");
				return obj;
			} else {
				shouKuanEntity.setShouKuanMoney(Double.valueOf(shouKuanMoney));// 收款金额
			}
			
			Matcher matchom = pattern.matcher(owedMoney);
			if (matchom.matches() == false) {
				obj.put("message", "还欠金额输入有误！");
				return obj;
			} else {
				shouKuanInfoEntity.setOwedMoney(Double.valueOf(owedMoney));// 还欠金额
			}

			// 判断是否为时间格式--
			String path = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}";// 定义匹配规则
			Pattern p = Pattern.compile(path);// 实例化Pattern
			Matcher m = p.matcher(payTime);// 验证字符串内容是否合法
			if (m.matches()) { // 使用正则验证
				System.out.println("输入的日期格式合法！");
				shouKuanInfoEntity.setPayTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(payTime));// 收款时间
			} else {
				obj.put("message", "收款时间输入有误啊！");
				return obj;
			}
			
			
			
			shouKuanInfoEntity.setUserinfoId(userInfoEntity);//用户添入数据库

			shoukuaninfoDao.save(shouKuanInfoEntity);
			ShouKuanInfoEntity shouKuanInfoEntity2 = shoukuaninfoDao.findOne(shouKuanInfoEntity.getShoukuanInfoId());
			shouKuanEntity.setShoukuaninfoId(shouKuanInfoEntity2);
			shoukuanDao.save(shouKuanEntity);
			System.out.println("操作成功！");
			obj.put("success", true);
		}
		return obj;
	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("delete/{id}")
	@ResponseBody
	// 指定使用jpa的事务管理器
	public JSONObject delete(@PathVariable("id") Long id) {
		JSONObject obj = new JSONObject();
		obj.put("success", false);
		ShouKuanEntity u;
		if (id != null && (u = shoukuanDao.findOne(id)) != null) {
			shoukuanDao.delete(u);
			obj.put("success", true);
		} else {
			obj.put("message", "此用户不存在！");
		}
		return obj;
	}

}
